package com.cloud.controller;

import com.alibaba.fastjson.JSONObject;
import com.cloud.config.SecurityCloudConfig;
import com.cloud.entity.ResultEntity;
import com.cloud.entity.UploadFileEntity;
import com.cloud.service.UploadFileService;
import com.cloud.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

import static com.cloud.util.UploadUtil.filesFromServlet;
import static com.cloud.util.UploadUtil.renameFiles;

/**
 * @author: 灿松
 * @description: 文件上传Controller
 * @date: 2017/10/24 16:04
 */
@RestController
@RequestMapping("/uploadfile")
public class UploadFileController {

	@Autowired
	private UploadFileService uploadFileService;

	@Autowired
	private SecurityCloudConfig securityCloudConfig;

	/**
	 * 查询上传文件
	 */
	//@RequiresPermissions("uploadFile:list")
	@GetMapping("/list")
	public ResultEntity listUploadFile(HttpServletRequest request) {
		JSONObject requestJson = CommonUtil.request2Json(request);
		return uploadFileService.listUploadFile(requestJson);
	}

	@PostMapping("/upload")
	public ResultEntity uploadFile(@RequestParam("file") MultipartFile multipartFile) throws IOException {
//		UploadFileEntity entity = uploadFileService.multipartFileToFileEntity(multipartFile);
		return uploadFileService.uploadFile(multipartFile);
	}

	/**
	 * 查询上传文件
	 */
	//@RequiresPermissions("uploadFile:list")
	@GetMapping("/query")
	public ResultEntity QueryUploadFile(HttpServletRequest request) {
		JSONObject requestJson = CommonUtil.request2Json(request);
		return uploadFileService.getUploadFileByCondition(requestJson);
	}

	/**
	 * 新增上传文件
	 */
	//@RequiresPermissions("uploadFile:add")
	@PostMapping("/add")
	public ResultEntity addUploadFile(@RequestBody UploadFileEntity entity) {
		CommonUtil.hasAllRequired(entity, "fileName, filePath");
		return uploadFileService.addUploadFile(entity);
	}

	/**
	 * 删除上传文件
	 */
	//@RequiresPermissions("uploadFile:update")
	@PostMapping("/delete")
	public ResultEntity deleteUploadFile(@RequestBody UploadFileEntity entity) {
		CommonUtil.hasAllRequired(entity, "id");
		return uploadFileService.removeUploadFile(entity);
	}

	/**
	 * nginx服务器上传后通知后台
	 * @param request
	 * @return
	 */
	@PostMapping("/notify")
	public ResultEntity notify(HttpServletRequest request) {
		List<UploadFileEntity> uploadFiles = filesFromServlet(request);
        List<UploadFileEntity> storeFiles = renameFiles(uploadFiles, securityCloudConfig.getStorePath());
		return uploadFileService.uploadNotify(storeFiles);
	}
}
